import React from 'react';
import { useState, useEffect } from 'react';

//自定义hooks;函数明勇use开头
const useFetch = (url) => {
    const [topics, setTopics] = useState([]);
    const [options, setOptions] = useState({ tab: 'all', page: 1 });
    useEffect(() => {
        fetch(url + '?tab=' + options.tab + '&page=' + options.page)
            .then(res => res.json())
            .then(res => {
                console.log(res);
                setTopics(res.data)
            })
    }, [options])
    //因为外面拿不到，所有必须要返回出
    return [topics, options, setOptions];
}

const Hooks = () => {
    // const [topics,setTopics] = useState([]);
    // useEffect(() => {
    //     fetch('https://cnodejs.org/api/v1/topics')
    //     .then(res => res.json())
    //     .then(res => {
    //         console.log(res);
    //         setTopics(res.data)
    //     }) 
    // }, [])
    const [topics, options, setOptions] = useFetch('https://cnodejs.org/api/v1/topics');

    return (
        <div>
            <header>
                <button onClick={() => setOptions({ tab: 'all', page: 1 })}>全部</button>
                <button onClick={() => setOptions({ tab: 'good', page: 1 })}>精华</button>
                <button onClick={() => setOptions({ tab: 'share', page: 1 })}>分享</button>
            </header>
            <header>
                <button onClick={() => setOptions({ ...options, page: 1 })}>1</button>
                <button onClick={() => setOptions({ ...options, page: 2 })}>2</button>
                <button onClick={() => setOptions({ ...options, page: 3 })}>3</button>
            </header>
            <header>
                <button onClick={() => setOptions('all')}>1</button>
                <button onClick={() => setOptions('good')}>2</button>
                <button onClick={() => setOptions('share')}>3</button>
            </header>

            {
                topics.map(item => <li key={item.id}>{item.title}</li>)
            }

        </div>
    )
}

export default Hooks
